<h1>用户列表 admin/user-list</h1>
<div class='row'>
  <div class='col-3'>
    <a href='/admin/user-create' type='button' class='btn btn-primary'>添加用户</a>
  </div>
</div>
<br/>
<div class="row">
  <form action="/admin/user-list" method="GET" class="col-3">
    <div class="input-group">
      <input type="text" placeholder="请输入关键字" class="form-control" name="keyword" value="{{keyword}}"/>
      <button class="btn btn-outline-secondary">搜索</button>
    </div>
  </form>
</div>
<br/>
<table class='table'>
  <thead>
    <tr>
      <th scope='col'>创建时间</th>
      <th scope='col'>创建时间</th>
      <th scope='col'>更新时间</th>
      <th scope='col'>状态</th>
      <th scope='col'>排序</th>
      <th scope='col'>操作</th>
    </tr>
  </thead>
  <tbody>
    {{#each users}}
    <tr class="custom-tr">
      <th scope='row'>{{this.username}}</th>
      <td>{{formatDate this.createdAt 'YYYY-MM-DD HH:mm:ss'}}</td>
      <td>{{formatDate this.updatedAt 'YYYY-MM-DD HH:mm:ss'}}</td>
      <td>
        <span data-bs-toggle="tooltip" data-bs-title="点击更新状态" class='status-toggle' data-id='{{this.id}}'
          data-status='{{this.status}}'>
          {{#if this.status}}
          <i class='bi bi-check-circle-fill text-success'></i>
          {{else}}
          <i class='bi bi-x-circle-fill text-danger'></i>
          {{/if}}
        </span>
      </td>
      <td style="width: 140px">
        <span class="sort-toggle" data-edit="0" data-id="{{this.id}}">
          <span data-bs-toggle="tooltip" data-bs-title="双击更新排序值" class="sort-text">
            {{this.sort}}
          </span>
          <input type="number" class="form-control sort-input" style="width: 80px" value="{{this.sort}}"/>
        </span>
      </td>
      <td>
        <a type='button' href='/admin/user/{{this.id}}/edit' class='btn btn-primary btn-sm'>编辑</a>
        <a type='button' class='btn btn-danger btn-sm' onclick='deleteUser({{this.id}})'>删除</a>
      </td>
    </tr>
    {{/each}}
  </tbody>
</table>
<nav aria-label="Page navigation example">
  <ul class="pagination">
    <li class="page-item">
      <div class="input-group me-3">
        <button class="btn btn-light">总数：{{total}}</button>
      </div>
    </li>
    <li class="page-item"><a class="btn btn-primary {{equal pageNo 1 'disabled'}}"  href="?pageNo={{decrease pageNo 1}}&pageSize={{pageSize}}&keyword={{keyword}}">上一页</a></li>
    {{#each (numberToArray pageTotal)}}
      <li class="page-item {{equal (parseInt ../pageNo) (summation this 1) 'active'}}">
        <a class="page-link" href="?pageNo={{summation this 1}}&pageSize={{../pageSize}}&keyword={{../keyword}}">{{summation this 1}}</a>
      </li>
    {{/each}}
    <li class="page-item"><a class="btn btn-primary {{equal pageTotal pageNo 'disabled'}}"  href="?pageNo={{summation pageNo 1}}&pageSize={{pageSize}}&keyword={{keyword}}">下一页</a></li>
    <li class="page-item">
      <form action="/admin/user-list" method="GET" class="d-inline-block ms-3">
        <input type="hidden" name="keyword" value="{{keyword}}"/>
        <input type="hidden" name="pageNo" value="{{pageNo}}"/>
        <div class="input-group">
          <input type="number" min="5" max="15" placeholder="size" class="form-control" name="pageSize" value="{{pageSize}}"/>
          <button class="btn btn-outline-secondary" type="submit">设置</button>
        </div>
      </form>
    </li>
  </ul>
</nav>
<script>
  function deleteUser(userId) {
    if (!confirm("确定要删除吗？")) return;
    axios({
      method: 'DELETE',
      url: `/admin/api-user/${userId}/delete`,
    }).then(({ data }) => {
      if (data.success) {
        const params = new URLSearchParams(window.location.search);
        let trs = document.querySelectorAll('.custom-tr');
        // 表示删除最后一个了
        if(trs.length === 1){
          const newPageNo = Number((params.get('pageNo') - 1))
          params.delete('pageNo');
          params.append('pageNo',String(Math.max(1, newPageNo)));
          window.location = window.location.pathname +'?'+ params.toString();
        }else{
          window.location.reload();
        }
      }
    })
  }
  window.onload = function () {
    let statusToggleEl = [...document.querySelectorAll('.status-toggle')];
    statusToggleEl.map((el) => {
      el.onclick = function () {
        const { id, status } = el.dataset;
        let newStatus = status === '1' ? '0' : '1';
        axios({
          method: "PUT",
          url: `/admin/api-user/${id}/edit`,
          header: {
            accept: "application/json",
          },
          data: {
            status: Number(newStatus)
          }
        }).then(({ data }) => {
          if (data.success) {
            el.dataset.status = String(newStatus);
            let map = {
              '1': `<i class='bi bi-check-circle-fill text-success'></i>`,
              '0': `<i class='bi bi-x-circle-fill text-danger'></i>`
            }
            el.innerHTML = map[newStatus]
          }
        })
      }
    })

    // bootstrap- tooltips组件使用
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
    const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))


    let sortToggleEls = [...document.querySelectorAll('.sort-toggle')];
    sortToggleEls.map((el) => {
      el.ondblclick = function () {
        const {edit,id} = el.dataset;
        let newEdit = edit === '0' ? '1' : '0';
        if(newEdit === '1'){
          el.dataset.edit = newEdit;
          let inputEl = el.querySelector('.sort-input');
          let textEl = el.querySelector('.sort-text');
          inputEl.focus();
          inputEl.onblur = function(event){
            let newSort = event.target.value;
            axios({
              method: "PUT",
              url: `/admin/api-user/${id}/edit`,
              header: {
                accept: "application/json",
              },
              data: {
                sort: Number(newSort)
              }
            }).then(({ data })=>{
              if(data.success){
                textEl.innerText = newSort;
                el.dataset.edit = '0';
              }
            })
          }
        }
      }
    })
  }
</script>

<style>
  .sort-toggle{
    cursor: pointer;
  }
  .sort-toggle[data-edit="0"] .sort-text,
  .sort-toggle[data-edit="1"] .sort-input {
    display: inherit;
  }
  .sort-toggle[data-edit="1"] .sort-text,
  .sort-toggle[data-edit="0"] .sort-input{
    display: none;
  }
  .page-item{
    cursor: pointer;
  }
</style>